﻿using System;
using System.IO;
using System.Text;
using Wangzeran.CodeMaker.Core.Tag;
using Wangzeran.CodeMaker.Core.Template;
using Wangzeran.CodeMaker.Core.Util;
using Wangzeran.CodeMaker.PlugIns.Tags;
using Wangzeran.CodeMaker.PlugIns.Util;

namespace Wangzeran.CodeMaker.PlugIns.Templates
{
    /// <summary>
    /// 文本模板
    /// </summary>
    public class TextTemplate : TemplateSupport
    {

        /// <summary>
        /// 模板名称
        /// </summary>
        public override string TemplateName
        {
            get { return "文本模板"; }
        }

        #region ITemplateSupport 成员
        /// <summary>
        /// 根据内容生成模板
        /// </summary>
        /// <param name="contents">模板内容</param>
        /// <returns></returns>
        public override string ExecuteTempldateContents(string contents, object value, out string fileName)
        {
            try
            {
                // 清空公共变量容器
                VariablesContainer.Variables.Clear();
                // 模板结果
                StringBuilder sbResult = new StringBuilder();
                // 获取多行标签
                StringBuilder sbTag = new StringBuilder();
                string[] templates = StringUtil.SplitString(contents);
                fileName = null;
                string tmp = null;
                string tagText = null;
                foreach (string line in templates)
                {
                    if (sbTag.Length == 0)
                    {
                        if (HasFullTag(line))       // 单行包括完整标签
                        {
                            sbTag.AppendLine(line);
                            // 获取标签（多个标签）
                            string[] tags = GetTags(line);
                            foreach (string tagStr in tags)
                            {
                                string tagResult = ProcessTag(tagStr, value, out tmp);
                                if (tmp != null)
                                {
                                    fileName = tmp;
                                }
                                sbTag = sbTag.Replace(tagStr, tagResult);
                                if (tagResult.Length == 0 && sbResult.Length > 0)
                                {
                                    sbResult = sbResult.Remove(sbResult.Length - Environment.NewLine.Length, 
                                        Environment.NewLine.Length);
                                }
                                //if (tagResult.Length == 0 && sbResult.Length > 0)
                                //{
                                //    sbResult.Remove(sbResult.Length - tagStr.Length, tagStr.Length);
                                //}
                            }
                            sbResult.Append(sbTag.ToString());
                            StringUtil.ClearStringBuilder(sbTag);
                        }
                        else if (HasBeginTag(line)) // 单行包括开始标签（多行标签）
                        {
                            sbTag.AppendLine(line);
                        }
                        else                        // 无标签行
                        {
                            sbResult.AppendLine(line);
                        }
                    }
                    else
                    {
                        sbTag.AppendLine(line);
                        if (HasEndTag(line))        // 包含结束标签（多行标签）
                        {
                            tagText = sbTag.ToString();
                            string tagResult = ProcessTag(tagText, value, out tmp);
                            sbTag = sbTag.Replace(tagText, tagResult);
                            sbResult.AppendLine(sbTag.ToString());
                            StringUtil.ClearStringBuilder(sbTag);
                        }
                    }
                }

                return sbResult.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据模板路径生成模板
        /// </summary>
        /// <param name="templatePath">模板路径</param>
        /// <returns></returns>
        public override string ExecuteTempldate(string templatePath, object value, out string fileName)
        {
            try
            {
                string contents = String.Empty;
                TextReader reader = new StreamReader(templatePath);
                contents = reader.ReadToEnd();

                return ExecuteTempldateContents(contents, value, out fileName);
            }
            catch (Exception ex)
            {	
                throw ex;
            }
        }


        #endregion
        /// <summary>
        /// 处理标签
        /// </summary>
        /// <param name="content">标签文本</param>
        /// <param name="value">标签值</param>
        /// <returns></returns>
        private string ProcessTag(string content, object value, out string fileName)
        {
            try
            {
                fileName = null;
                string tagResult = String.Empty;
                ITag tag = ParseTag(content);
                if (tag == null)
                {
                    return content;
                }
                tagResult = tag.Process(content, value);
                if (tag is FileNameTag)
                {
                    fileName = tagResult;
                    return String.Empty;
                }
                return tagResult;
            }
            catch (Exception ex)
            {	
                throw ex;
            }
        }

    }
}
